﻿using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WinSat
{
    public partial class frmSiparis : Form
    {
        public string EvrakSeri { get; set; }
        public int EvrakSira { get; set; }
        public bool EskiEvrak { get; set; }

        public Cari Cari { get; set; }
        private DataTable Hareket = new DataTable();

        public frmSiparis()
        {
            InitializeComponent();
            Hareket.Columns.Add("Stok Kodu", typeof(string));
            Hareket.Columns.Add("Stok Adı", typeof(string));
            Hareket.Columns.Add("Miktar", typeof(decimal));
            Hareket.Columns.Add("Birim", typeof(string));
            Hareket.Columns.Add("Fiyat", typeof(decimal));
            Hareket.Columns.Add("İsk1", typeof(decimal));
            Hareket.Columns.Add("İsk2", typeof(decimal));
            Hareket.Columns.Add("İsk3", typeof(decimal));
            Hareket.Columns.Add("Tutar", typeof(decimal));
            Hareket.Columns.Add("Barkod", typeof(string));
            Hareket.Columns.Add("Kdv", typeof(int));
            Hareket.Columns.Add("kdvtutari", typeof(decimal));
            Hareket.Columns.Add("doviz", typeof(string));
            Hareket.Columns.Add("aciklama", typeof(string));
            Hareket.Columns.Add("brtfiyat", typeof(decimal));

            dataGrid1.VeriKaynagi = Hareket;
            dataGrid1.Columns[0].Width = 0;
            dataGrid1.Columns[1].Width = 150;
            dataGrid1.Columns[3].Width = 0;
            dataGrid1.Columns[5].Width = 0;
            dataGrid1.Columns[6].Width = 0;
            dataGrid1.Columns[7].Width = 0;
            dataGrid1.Columns[9].Width = 75;
            dataGrid1.Columns[10].Width = 0;
            dataGrid1.Columns[11].Width = 0;
            dataGrid1.Columns[12].Width = 0;
            dataGrid1.Columns[13].Width = 0;
            dataGrid1.Columns[14].Width = 0;
        }

        private decimal DovizKur(string parabirimi)
        {
            decimal kur = 1;
            try
            {
                using (Query q = new Query())
                {
                    q.Add(string.Format("SELECT     rate  FROM         CURRENCY  WHERE     (name = '{0}')", parabirimi));
                    kur = q.ExecScaler<decimal>();
                    if (kur == 0) kur = 1;
                }
            }
            catch (Exception)
            {
            }
            return kur;
        }

        private string DovizConvert(string deger)
        {
            string simge = "";
            switch (deger)
            {
                case "0":
                    simge = "TL";
                    break;
                case "1":
                    simge = "USD";
                    break;
                case "2":
                    simge = "EURO";
                    break;
                default:
                    simge = "TL";
                    break;
            }
            return simge;
        }

        private void EskiEvrakOku()
        {
            using (Query q = new Query())
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(" SELECT t1.product_code, t2.name, t1.amount, t2.unit, (t1.total / t1.amount) AS netfiyat,t1.discount1, t1.discount2, t1.discount3, t1.total, t1.barcode, t1.vat,t1.vatsum,cast(t1.currency as nvarchar(5)) as currency, t1.comment, t1.price AS brtfiyat ");
                sb.Append(" FROM         ORDER_DETAILS as t1  WITH (NOLOCK)  INNER JOIN PRODUCTS as t2  WITH (NOLOCK) ON t1.barcode = t2.barcode ");
                sb.AppendFormat(" WHERE     (t1.order_series = '{0}') AND (t1.order_no = {1}) ", this.EvrakSeri, this.EvrakSira);
                q.Add(sb.ToString());

                DataTable dt = q.Fill();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    switch (dt.Rows[i]["currency"].ToString())
                    {
                        case "0":
                            dt.Rows[i]["currency"] = "TL";
                            break;
                        case "1":
                            dt.Rows[i]["currency"] = "USD";
                            break;
                        case "2":
                            dt.Rows[i]["currency"] = "EURO";
                            break;
                    }
                    Hareket.Rows.Add(dt.Rows[i].ItemArray);
                }
            }
        }


        private void frmSiparis_Load(object sender, EventArgs e)
        {
            try
            {
                if (this.EskiEvrak)
                {
                    EskiEvrakOku();
                }
                else
                {
                    this.EvrakSira = CariSira(this.EvrakSeri);
                }
            }
            catch (Exception ex)
            {
                ExceptionHandling.Hand(ex);
            }
            txtBarkod.Focus();
        }

        private decimal[] SubTotal()
        {
            decimal fiyat = 0;
            decimal miktar = 0;
            decimal tutar = 0;
            decimal kdv_orani = 0;
            decimal kdv_tutar = 0;
            decimal geneltoplam = 0;
            decimal kdv_toplam = 0;
            decimal isk1oran;
            decimal isk2oran;
            decimal isk3oran;
            decimal isk1tutar;
            decimal isk2tutar;
            decimal isk3tutar;
            decimal genelisk1tutar = 0;
            decimal genelisk2tutar = 0;
            decimal genelisk3tutar = 0;


            for (int i = 0; i < dataGrid1.RowCount; i++)
            {
                if (dataGrid1[i, 0] != null)
                {
                    if (dataGrid1[i, 2] != null) miktar = Convert.ToDecimal(dataGrid1[i, 2]); else miktar = 0;
                    if (dataGrid1[i, 4] != null) fiyat = Convert.ToDecimal(dataGrid1[i, 14]); else fiyat = 0;
                    tutar = miktar * fiyat;
                    isk1oran = Convert.ToDecimal(dataGrid1[i, 5]);
                    isk2oran = Convert.ToDecimal(dataGrid1[i, 6]);
                    isk3oran = Convert.ToDecimal(dataGrid1[i, 7]);
                    isk1tutar = tutar * isk1oran / 100;
                    isk2tutar = (tutar - isk1tutar) * isk2oran / 100;
                    isk3tutar = (tutar - isk1tutar - isk2tutar) * isk3oran / 100;
                    genelisk1tutar += isk1tutar;
                    genelisk2tutar += isk2tutar;
                    genelisk3tutar += isk3tutar;

                    tutar = tutar - isk1tutar - isk2tutar - isk3tutar;
                    dataGrid1[i, 8] = tutar.ToString("#,###.00");

                    if (dataGrid1[i, 10] != null) kdv_orani = Convert.ToDecimal(dataGrid1[i, 10]); else kdv_orani = 0;
                    //kdv_orani = 0;
                    kdv_tutar = tutar * kdv_orani / 100;
                    dataGrid1[i, 11] = kdv_tutar;

                    kdv_toplam += kdv_tutar;
                    geneltoplam += tutar;
                }
            }

            decimal[] dizi = new decimal[8];
            dizi[0] = (geneltoplam + genelisk1tutar + genelisk2tutar + genelisk3tutar); //txtAraToplam.Text
            dizi[1] = genelisk1tutar;//txtisk1.Text
            dizi[2] = genelisk2tutar;//txtisk2.Text
            dizi[3] = genelisk3tutar;//txtisk3.Text
            dizi[4] = geneltoplam;//txtNetToplam.Text
            dizi[5] = kdv_toplam;//txtKdvToplam.Text
            dizi[6] = (geneltoplam + kdv_toplam);//txtGenelToplam.Text
            return dizi;
        }


        private int ConvertDoviz(string doviz)
        {
            switch (doviz)
            {
                case "TL":
                    return 0;
                case "USD":
                    return 1;
                case "EURO":
                    return 2;
                default:
                    return 0;
            }
        }

        private string getVal(int row, int col)
        {
            string sonuc = string.Empty;
            try
            {

                if (dataGrid1[row, col] != null)
                    if (string.IsNullOrEmpty(dataGrid1[row, col].ToString()) == false)
                        sonuc = dataGrid1[row, col].ToString();
            }
            catch (Exception ex)
            {
                ExceptionHandling.Hand(ex);
            }
            return sonuc;
        }

        private void EvrakKayit()
        {
            try
            {
                string order_series = EvrakSeri;
                int order_no = EvrakSira;
                DateTime order_date = DateTime.Now;
                string customer_code = Cari.Kodu;

                string product_code = string.Empty;
                string barcode = string.Empty;
                decimal amount = decimal.MinValue;
                decimal price = decimal.MinValue;
                decimal total = decimal.MinValue;
                int vat = int.MinValue;
                decimal vatsum = decimal.MinValue;
                int currency = int.MinValue;
                decimal isk1;
                decimal isk2;
                decimal isk3;
                decimal isk1tutar;
                decimal isk2tutar;
                decimal isk3tutar;

                using (Query q = new Query())
                {
                    //q.OpenTran();
                    string insertSql = "insert into ORDER_DETAILS (order_series, order_no, order_date, customer_code, product_code, barcode, amount, price, total, vat, vatsum, currency,supplier,printed,discount1,discount2,discount3,comment,terminal) values (@order_series, @order_no, @order_date, @customer_code, @product_code, @barcode, @amount, @price, @total, @vat, @vatsum, @currency,@supplier,1,@isk1,@isk2,@isk3,@comment,0)";
                    string deleteSql = " delete from ORDER_DETAILS where order_series=@order_series and order_no=@order_no";


                    q.Add("@order_series", SqlDbType.NVarChar, order_series, 5);
                    q.Add("@order_no", SqlDbType.Int, order_no);
                    q.Add(deleteSql);
                    q.Exec();
                    q.Clear();

                    q.Add("@order_series", SqlDbType.NVarChar, order_series, 5); //1
                    q.Add("@order_no", SqlDbType.Int, order_no); //2
                    q.Add("@order_date", SqlDbType.DateTime, order_date);  //3
                    q.Add("@customer_code", SqlDbType.NVarChar, customer_code, 25); //4
                    q.Add("@product_code", SqlDbType.NVarChar, "", 25); //5
                    q.Add("@barcode", SqlDbType.NVarChar, 25); //6
                    q.Add("@amount", SqlDbType.Float, 0M); //7
                    q.Add("@price", SqlDbType.Float, 0M); //8
                    q.Add("@total", SqlDbType.Float, 0M); //9
                    q.Add("@vat", SqlDbType.Int, 0); //10
                    q.Add("@vatsum", SqlDbType.Float, 0M); //11
                    q.Add("@currency", SqlDbType.Int, 0); //12
                    q.Add("@supplier", SqlDbType.NVarChar, Program.Session[Settings.Tedarikci].ToString()); //13
                    q.Add("@isk1", SqlDbType.Float, 0M); //14
                    q.Add("@isk2", SqlDbType.Float, 0M); //15
                    q.Add("@isk3", SqlDbType.Float, 0M); //16
                    q.Add("@comment", SqlDbType.NVarChar, "", 500); //17
                    q.Add(insertSql);

                    for (int i = 0; i < dataGrid1.RowCount; i++)
                    {
                        if (dataGrid1[i, 0] != null)
                        {
                            q.SetParamValue(16, getVal(i, 13));
                            product_code = getVal(i, 0);
                            amount = decimal.Parse(getVal(i, 2).Replace('.', ','));
                            price = decimal.Parse(getVal(i, 14).Replace('.', ','));
                            isk1 = decimal.Parse(getVal(i, 5).Replace('.', ','));
                            isk2 = decimal.Parse(getVal(i, 6).Replace('.', ','));
                            isk3 = decimal.Parse(getVal(i, 7).Replace('.', ','));
                            barcode = getVal(i, 9);

                            total = amount * price;

                            isk1tutar = total * isk1 / 100;
                            isk2tutar = (total - isk1tutar) * isk2 / 100;
                            isk3tutar = (total - isk1tutar - isk2tutar) * isk3 / 100;
                            total = total - isk1tutar - isk2tutar - isk3tutar;

                            vat = int.Parse(getVal(i, 10));
                            vatsum = total / 100m * vat;
                            currency = ConvertDoviz(getVal(i, 12));

                            q.SetParamValue(4, product_code);
                            q.SetParamValue(5, barcode);
                            q.SetParamValue(6, amount);
                            q.SetParamValue(7, price);
                            q.SetParamValue(8, total);
                            q.SetParamValue(9, vat);
                            q.SetParamValue(10, vatsum);
                            q.SetParamValue(11, currency);
                            q.SetParamValue(13, isk1);
                            q.SetParamValue(14, isk2);
                            q.SetParamValue(15, isk3);

                            q.Exec();

                        }
                    }

                    q.Clear();

                    if (Program.Session[Settings.BaglantiTipi].ToString() != "local")
                    {
                        q.Add(string.Format("UPDATE ORDER_DETAILS SET printed=0,terminal=1 WHERE (order_series = '{0}') AND (order_no = {1}) ", order_series, order_no));
                        q.Exec();
                    }


                    q.Clear();

                    CekilisKontrol(SubTotal()[4], order_series, order_no, customer_code, q);


                    //q.Commit();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void EvrakKayit(int i)
        {
            try
            {
                string order_series = EvrakSeri;
                int order_no = EvrakSira;
                DateTime order_date = DateTime.Now;
                string customer_code = Cari.Kodu;

                string product_code = string.Empty;
                string barcode = string.Empty;
                decimal amount = decimal.MinValue;
                decimal price = decimal.MinValue;
                decimal total = decimal.MinValue;
                int vat = int.MinValue;
                decimal vatsum = decimal.MinValue;
                int currency = int.MinValue;
                decimal isk1;
                decimal isk2;
                decimal isk3;
                decimal isk1tutar;
                decimal isk2tutar;
                decimal isk3tutar;

                using (Query q = new Query())
                {
                    //q.OpenTran();
                    string insertSql = "insert into ORDER_DETAILS (order_series, order_no, order_date, customer_code, product_code, barcode, amount, price, total, vat, vatsum, currency,supplier,printed,discount1,discount2,discount3,comment,terminal) values (@order_series, @order_no, @order_date, @customer_code, @product_code, @barcode, @amount, @price, @total, @vat, @vatsum, @currency,@supplier,1,@isk1,@isk2,@isk3,@comment,0)";
                    //string deleteSql = " delete from ORDER_DETAILS where order_series=@order_series and order_no=@order_no";


                    //q.Add("@order_series", SqlDbType.NVarChar, order_series, 5);
                    //q.Add("@order_no", SqlDbType.Int, order_no);
                    //q.Add(deleteSql);
                    //q.Exec();
                    //q.Clear();

                    q.Add("@order_series", SqlDbType.NVarChar, order_series, 5); //1
                    q.Add("@order_no", SqlDbType.Int, order_no); //2
                    q.Add("@order_date", SqlDbType.DateTime, order_date);  //3
                    q.Add("@customer_code", SqlDbType.NVarChar, customer_code, 25); //4
                    q.Add("@product_code", SqlDbType.NVarChar, "", 25); //5
                    q.Add("@barcode", SqlDbType.NVarChar, 25); //6
                    q.Add("@amount", SqlDbType.Float, 0M); //7
                    q.Add("@price", SqlDbType.Float, 0M); //8
                    q.Add("@total", SqlDbType.Float, 0M); //9
                    q.Add("@vat", SqlDbType.Int, 0); //10
                    q.Add("@vatsum", SqlDbType.Float, 0M); //11
                    q.Add("@currency", SqlDbType.Int, 0); //12
                    q.Add("@supplier", SqlDbType.NVarChar, Program.Session[Settings.Tedarikci].ToString()); //13
                    q.Add("@isk1", SqlDbType.Float, 0M); //14
                    q.Add("@isk2", SqlDbType.Float, 0M); //15
                    q.Add("@isk3", SqlDbType.Float, 0M); //16
                    q.Add("@comment", SqlDbType.NVarChar, "", 500); //17
                    q.Add(insertSql);

                    if (dataGrid1[i, 0] != null)
                    {
                        q.SetParamValue(16, getVal(i, 13));
                        product_code = getVal(i, 0);
                        amount = decimal.Parse(getVal(i, 2).Replace('.', ','));
                        price = decimal.Parse(getVal(i, 14).Replace('.', ','));
                        isk1 = decimal.Parse(getVal(i, 5).Replace('.', ','));
                        isk2 = decimal.Parse(getVal(i, 6).Replace('.', ','));
                        isk3 = decimal.Parse(getVal(i, 7).Replace('.', ','));
                        barcode = getVal(i, 9);

                        total = amount * price;

                        isk1tutar = total * isk1 / 100;
                        isk2tutar = (total - isk1tutar) * isk2 / 100;
                        isk3tutar = (total - isk1tutar - isk2tutar) * isk3 / 100;
                        total = total - isk1tutar - isk2tutar - isk3tutar;

                        vat = int.Parse(getVal(i, 10));
                        vatsum = total / 100m * vat;
                        currency = ConvertDoviz(getVal(i, 12));

                        q.SetParamValue(4, product_code);
                        q.SetParamValue(5, barcode);
                        q.SetParamValue(6, amount);
                        q.SetParamValue(7, price);
                        q.SetParamValue(8, total);
                        q.SetParamValue(9, vat);
                        q.SetParamValue(10, vatsum);
                        q.SetParamValue(11, currency);
                        q.SetParamValue(13, isk1);
                        q.SetParamValue(14, isk2);
                        q.SetParamValue(15, isk3);

                        q.Exec();

                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void CekilisOlustur(string seri, int sira, string saglayici, string cari, string cekilisno, decimal tutar, Query q)
        {
            try
            {
                q.Clear();
                StringBuilder sb = new StringBuilder();
                sb.Append("if exists(select rec_id from CEKILIS_HAREKET  WITH (NOLOCK) where siparis_seri=@siparis_seri and siparis_no=@siparis_no )");
                sb.Append("update CEKILIS_HAREKET set saglayici=@saglayici,cari=@cari,siparis_tutari=@siparis_tutari,cekilis_no=@cekilis_no where siparis_seri=@siparis_seri and siparis_no=@siparis_no  else ");
                sb.Append("insert into CEKILIS_HAREKET (cari,saglayici,siparis_tutari,siparis_seri,siparis_no,cekilis_no) values (@cari,@saglayici,@siparis_tutari,@siparis_seri,@siparis_no,@cekilis_no) ");

                q.Add("@siparis_tutari", SqlDbType.Float, tutar);
                q.Add("@cekilis_no", SqlDbType.NVarChar, cekilisno, 25);
                q.Add("@siparis_seri", SqlDbType.NVarChar, seri, 5);
                q.Add("@siparis_no", SqlDbType.Int, sira);
                q.Add("@cari", SqlDbType.NVarChar, cari, 25);
                q.Add("@saglayici", SqlDbType.NVarChar, saglayici, 25);

                q.Add(sb.ToString());
                q.Exec();
            }
            catch (Exception ex)
            {
                ExceptionHandling.Hand(ex);
            }
        }

        private void CekilisKontrol(decimal siparisTutari, string seri, int sira, string cari, Query q)
        {
            try
            {
                q.Clear();
                string cekilisNo = "";
                string supplier = Program.Session[Settings.Tedarikci].ToString();
                q.Add(string.Format("SELECT     cekilis_no  FROM         CEKILISLER WITH (NOLOCK)  WHERE     (tedarikci_kodu = '{0}') AND (cekilis_limit <= @tutar)", supplier));
                q.Add("@tutar", SqlDbType.Float, siparisTutari);

                object sonuc = q.ExecScaler<object>();
                if (sonuc != null)
                {
                    cekilisNo = sonuc.ToString();
                    CekilisOlustur(seri, sira, supplier, cari, cekilisNo, siparisTutari, q);
                }
            }
            catch (Exception ex)
            {
                ExceptionHandling.Hand(ex);
            }
        }


        //public DataTable StokListeKod(string filtre)
        //{
        //    DataTable sonuc;
        //    using (Query q = new Query())
        //    {
        //        q.Add("@kod", SqlDbType.NVarChar, "%" + filtre + "%", 25);
        //        q.Add("@satici", SqlDbType.NVarChar, Program.Session[Settings.Tedarikci], 25);
        //        q.Add("SELECT     MAX(barcode) AS Barkod, code AS [Ürün Kodu], name AS [Ürün Adı], price AS Fiyatı,vat as Kdv,dbo.DovizConvert(currency) as Döviz,isnull(discount1,0) as İsk1,isnull(discount2,0) as İsk2,isnull(discount3,0) as İsk3,unit as Birim FROM         PRODUCTS WITH (NOLOCK)  WHERE     (supplier = @satici) AND (code LIKE @kod) GROUP BY code, name, price, vat, dbo.DovizConvert(currency), ISNULL(discount1, 0), ISNULL(discount2, 0), ISNULL(discount3, 0), unit");
        //        sonuc = q.Fill();
        //    }
        //    return sonuc;
        //}

        public DataTable StokListeAd(string filtre)
        {
            DataTable sonuc;
            using (Query q = new Query())
            {
                q.Add("@kod", SqlDbType.NVarChar, "%" + filtre + "%", 25);
                q.Add("@satici", SqlDbType.NVarChar, Program.Session[Settings.Tedarikci], 25);
                q.Add("SELECT     name AS [Ürün Adı],price AS Fiyatı,MAX(barcode) AS Barkod, code AS [Ürün Kodu],vat as Kdv,currency as Döviz,discount1 as İsk1,discount2 as İsk2,discount3 as İsk3,unit as Birim FROM         PRODUCTS WITH (NOLOCK)  WHERE     (supplier = @satici) AND (name LIKE @kod) GROUP BY name, price, code, vat, currency, discount1, discount2, discount3, unit");
                sonuc = q.Fill();
            }
            return sonuc;
        }

        private void Yeni()
        {
            txtBarkod.Text = string.Empty;
            txtBarkod.Tag = string.Empty;
            txtStokAdi.Text = string.Empty;
            txtFiyat.Text = string.Empty;
            txtKdv.Text = string.Empty;
            txtDoviz.Text = string.Empty;
            txtIsk1.Text = string.Empty;
            txtIsk2.Text = string.Empty;
            txtIsk3.Text = string.Empty;
            txtBirim.Text = string.Empty;
            txtAciklama.Text = string.Empty;
            txtMiktar.Text = string.Empty;
            txtBarkod.Focus();
        }

        public void UrunBul(string filtre)
        {
            Yeni();
            object obj = null;
            using (Query q = new Query())
            {
                q.Add("@kod", SqlDbType.NVarChar, filtre, 25);
                q.Add("@satici", SqlDbType.NVarChar, Program.Session[Settings.Tedarikci], 25);
                if (Program.Session[Settings.BaglantiTipi].ToString() == "local")
                {
                    q.Add("SELECT     (barcode + ';' + code + ';' + name + ';' + replace(cast(price as nvarchar(20)),'.',',') + ';' + cast(vat as nvarchar) + ';' + cast(currency as nvarchar(20)) + ';' + replace(cast(discount1 as nvarchar(20)),'.',',') + ';' + replace(cast(discount2 as nvarchar(20)),'.',',') + ';' + replace(cast(discount3 as nvarchar(20)),'.',',') + ';' + unit ) as bilgi FROM         PRODUCTS  WITH (NOLOCK) WHERE     (supplier = @satici) AND (barcode=@kod or code=@kod) ");
                }
                else
                {
                    q.Add("SELECT     (barcode + ';' + isnull(code,'') + ';' + name + ';' + replace(cast(price as nvarchar(20)),'.',',') + ';' + cast(vat as nvarchar) + ';' + cast(currency as nvarchar(20)) + ';' + replace(cast(isnull(discount1,0) as nvarchar(20)),'.',',') + ';' + replace(cast(isnull(discount2,0) as nvarchar(20)),'.',',') + ';' + replace(cast(isnull(discount3,0) as nvarchar(20)),'.',',') + ';' + unit ) as bilgi FROM         PRODUCTS  WITH (NOLOCK) WHERE     (supplier = @satici) AND (barcode=@kod or code=@kod) ");
                }
                obj = q.ExecScaler<object>();
            }
            if (obj != null)
            {
                string[] alanlar = obj.ToString().Split(';');
                txtBarkod.Text = alanlar[0];
                txtBarkod.Tag = alanlar[1];
                txtStokAdi.Text = alanlar[2];
                txtFiyat.Text = (DovizKur(DovizConvert(alanlar[5])) * Cevir.Parse<decimal>(alanlar[3].Replace('.', ','))).ToString("n3");
                txtKdv.Text = alanlar[4];
                txtDoviz.Text = DovizConvert(alanlar[5]);
                txtIsk1.Text = alanlar[6].Replace('.', ',');
                txtIsk2.Text = alanlar[7].Replace('.', ',');
                txtIsk3.Text = alanlar[8].Replace('.', ',');
                txtBirim.Text = alanlar[9];
                txtMiktar.Focus();
            }
            else
            {
                MessageBox.Show("Ürün Bulunamadı");
                txtBarkod.SelectAll();
                txtBarkod.Focus();
            }
        }

        public int CariSira(string seri)
        {
            int sira = 1;
            using (Query q = new Query())
            {
                q.Add("@kod", SqlDbType.NVarChar, seri, 25);
                q.Add("SELECT     MAX(order_no) FROM ORDER_DETAILS  WITH (NOLOCK) WHERE (order_series = @kod) ");
                sira = q.ExecScaler<int>() + 1;
                q.Clear();

                q.Add("@kod", SqlDbType.NVarChar, seri, 25);
                q.Add("@sira", SqlDbType.NVarChar, sira, 25);
                q.Add("insert into ORDER_DETAILS (order_series,order_no) values (@kod,@sira) ");
                q.Exec();
            }
            return sira;
        }

        private void txtBarkod_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    try
                    {
                        Cursor.Current = Cursors.WaitCursor;
                        UrunBul(txtBarkod.Text);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Lütfen tekrar deneyin !");
                    }
                    finally
                    {
                        Cursor.Current = Cursors.Default;
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionHandling.Hand(ex);
            }
        }

        private void btnEkle_Click(object sender, EventArgs e)
        {
            try
            {
                Ekle();
                EvrakKayit(Hareket.Rows.Count - 1);
            }
            catch (Exception)
            {
                MessageBox.Show("Lütfen Miktar giriniz !");
            }
        }

        private void Ekle()
        {
            if (!string.IsNullOrEmpty(txtFiyat.Text) && !string.IsNullOrEmpty(txtMiktar.Text) && !string.IsNullOrEmpty(txtBarkod.Text))
            {
                decimal total = Cevir.Parse<decimal>(txtMiktar.Text) * Cevir.Parse<decimal>(txtFiyat.Text);
                decimal isk1tutar = total * Cevir.Parse<decimal>(txtIsk1.Text) / 100;
                decimal isk2tutar = (total - isk1tutar) * Cevir.Parse<decimal>(txtIsk2.Text) / 100;
                decimal isk3tutar = (total - isk1tutar - isk2tutar) * Cevir.Parse<decimal>(txtIsk3.Text) / 100;
                total = Cevir.Parse<decimal>((total - isk1tutar - isk2tutar - isk3tutar).ToString("n2"));

                decimal fiyat = Cevir.Parse<decimal>((total / Cevir.Parse<decimal>(txtMiktar.Text)).ToString("n2"));

                Hareket.Rows.Add(txtBarkod.Tag, txtStokAdi.Text, Cevir.Parse<decimal>(txtMiktar.Text), txtBirim.Text, fiyat,
                    Cevir.Parse<decimal>(txtIsk1.Text), Cevir.Parse<decimal>(txtIsk2.Text), Cevir.Parse<decimal>(txtIsk3.Text), total, txtBarkod.Text,
                    Cevir.Parse<int>(txtKdv.Text), 0, txtDoviz.Text, txtAciklama.Text, Cevir.Parse<decimal>(txtFiyat.Text));
                Yeni();
            }
            else
            {
                MessageBox.Show("Eksik Bilgi Girişi Yapıldı !");
            }
        }

        private void btnKapat_Click(object sender, EventArgs e)
        {
            try
            {
                this.Close();
            }
            catch (Exception ex)
            {
                ExceptionHandling.Hand(ex);
            }
        }

        bool klavyeAcik = false;
        private void btnKlavye_Click(object sender, EventArgs e)
        {
            if (klavyeAcik)
            {
                klavyeAcik = false;
                Sip.Hide();
            }
            else
            {
                klavyeAcik = true;
                Sip.Show();
            }
        }

        private void btnYeni_Click(object sender, EventArgs e)
        {
            try
            {
                Yeni();
            }
            catch (Exception ex)
            {
                ExceptionHandling.Hand(ex);
            }
        }

        private void btnSorgu_Click(object sender, EventArgs e)
        {
            try
            {
                gridView1.VeriKaynagi = StokListeAd(txtBarkod.Text);
                gridView1.Columns[0].Width = 200;
                gridView1.Columns[1].Width = 75;
                gridView1.Columns[2].Width = 100;
                tabControl1.SelectedIndex = 1;
            }
            catch (Exception ex)
            {
                ExceptionHandling.Hand(ex);
            }
        }

        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                if (gridView1.RowCount > 0 && gridView1.CurrentRowIndex > -1)
                {
                    txtStokAdi.Text = gridView1[gridView1.CurrentRowIndex, 0].ToString();
                    decimal fiyat = Cevir.Parse<decimal>(gridView1[gridView1.CurrentRowIndex, 1].ToString());
                    string dovizAdi = DovizConvert(gridView1[gridView1.CurrentRowIndex, 5].ToString());

                    txtFiyat.Text = (DovizKur(dovizAdi) * fiyat).ToString("n3");
                    txtBarkod.Text = gridView1[gridView1.CurrentRowIndex, 2].ToString();
                    txtBarkod.Tag = gridView1[gridView1.CurrentRowIndex, 3].ToString();
                    txtKdv.Text = gridView1[gridView1.CurrentRowIndex, 4].ToString();
                    txtDoviz.Text = dovizAdi;
                    txtIsk1.Text = gridView1[gridView1.CurrentRowIndex, 6].ToString();
                    txtIsk2.Text = gridView1[gridView1.CurrentRowIndex, 7].ToString();
                    txtIsk3.Text = gridView1[gridView1.CurrentRowIndex, 8].ToString();
                    txtBirim.Text = gridView1[gridView1.CurrentRowIndex, 9].ToString();
                    tabControl1.SelectedIndex = 0;
                    txtMiktar.Focus();
                }
            }
            catch (Exception ex)
            {
                ExceptionHandling.Hand(ex);
            }
        }

        private void btnIptal_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult dlg = MessageBox.Show("Satır'ı Silmek istediğinize eminmisiniz ?", "Uyarı", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                if (dlg == DialogResult.Yes)
                {
                    if (dataGrid1.CurrentRowIndex > -1 && !string.IsNullOrEmpty(Hareket.Rows[dataGrid1.CurrentRowIndex][0].ToString()))
                    {
                        string stokkodu = Hareket.Rows[dataGrid1.CurrentRowIndex][0].ToString();
                        using (Query q = new Query())
                        {
                            List<int> _sil = new List<int>();
                            for (int i = 0; i < Hareket.Rows.Count; i++)
                            {
                                if (stokkodu == Hareket.Rows[i][0].ToString())
                                {
                                    q.Add(string.Format("delete from ORDER_DETAILS WHERE order_series='{0}' and order_no={1} and product_code='{2}'", EvrakSeri, EvrakSira, stokkodu));
                                    q.Exec();
                                    _sil.Add(i);
                                }
                            }
                            foreach (var item in _sil)
                            {
                                Hareket.Rows.RemoveAt(item);
                            }
                        }
                    }
                }
                dataGrid1.Refresh();
                Yeni();
            }
            catch (Exception ex)
            {
                ExceptionHandling.Hand(ex);
            }
        }

        private void btnSil_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult dlg = MessageBox.Show("Evrağın tümünü silmek istediğinize eminmisiniz ?", "Uyarı", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                if (dlg == DialogResult.Yes)
                {
                    Hareket.Rows.Clear();
                }
                dataGrid1.Refresh();
                Yeni();
            }
            catch (Exception ex)
            {
                ExceptionHandling.Hand(ex);
            }
        }

        private void txtMiktar_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    Ekle();
                    EvrakKayit(Hareket.Rows.Count - 1);
                }
            }
            catch (Exception ex)
            {
                ExceptionHandling.Hand(ex);
            }
        }

        private void txtFiyat_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtIsk1.Focus();
            }
        }

        private void txtIsk1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtIsk2.Focus();
            }
        }

        private void txtIsk2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtIsk3.Focus();
            }
        }

        private void txtIsk3_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtMiktar.Focus();
            }
        }

        private void btnToplamlar_Click(object sender, EventArgs e)
        {
            try
            {
                frmToplamlar top = new frmToplamlar();
                top.Seri = EvrakSeri;
                top.Sira = EvrakSira.ToString();
                top.Firma = Cari;
                top.Toplamlar = SubTotal();
                top.Show();
            }
            catch (Exception ex)
            {
                ExceptionHandling.Hand(ex);
            }
        }

        private void frmSiparis_Closing(object sender, CancelEventArgs e)
        {
            if (dataGrid1.RowCount > 0)
            {
                DialogResult res = MessageBox.Show("Evrağı Kaydetmek İstermisiniz ?", "Uyarı", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                if (res == DialogResult.No)
                {
                    try
                    {
                        Cursor.Current = Cursors.WaitCursor;
                        if (!EskiEvrak)
                        {
                            using (Query q = new Query())
                            {
                                q.Add(string.Format("DELETE FROM ORDER_DETAILS WHERE (order_series = '{0}') AND (order_no = {1}) ", EvrakSeri, EvrakSira));
                                q.Exec();
                            }
                        }
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Kaydedilemedi tekrar deneyin !");
                        e.Cancel = true;
                    }
                    finally
                    {
                        Cursor.Current = Cursors.Default;
                    }
                }
                else if (res == DialogResult.Yes)
                {
                    if (Program.Session[Settings.BaglantiTipi].ToString() != "local")
                    {
                        using (Query q = new Query())
                        {
                            q.Add(string.Format("UPDATE ORDER_DETAILS SET printed=0,terminal=1 WHERE (order_series = '{0}') AND (order_no = {1}) ", EvrakSeri, EvrakSira));
                            q.Exec();
                        }
                    }
                }
                else if (res == DialogResult.Cancel)
                    e.Cancel = true;
            }
        }

        private void txtMiktar_TextChanged(object sender, EventArgs e)
        {
            if (txtMiktar.TextLength > 7)
            {
                txtMiktar.Text = "";
                MessageBox.Show("Miktar alanına barkod girdiniz !");
            }
        }

    }
}